package com.microservice.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * RestTemplate 配置类
 * 通用的HTTP客户端配置
 * 所有服务自动共享此配置
 */
@Configuration
public class RestTemplateConfig {
    
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000); // 连接超时5秒
        factory.setReadTimeout(5000);    // 读取超时5秒
        
        RestTemplate restTemplate = new RestTemplate(factory);
        
        // 获取现有的消息转换器列表
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        
        // 配置 MappingJackson2HttpMessageConverter 支持 text/plain
        for (HttpMessageConverter<?> converter : messageConverters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
                List<MediaType> supportedMediaTypes = new ArrayList<>(jsonConverter.getSupportedMediaTypes());
                // 添加 text/plain 支持，让它也能被当作 JSON 处理
                supportedMediaTypes.add(MediaType.TEXT_PLAIN);
                supportedMediaTypes.add(new MediaType("application", "*+json"));
                jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
            }
            // 配置 StringHttpMessageConverter 使用 UTF-8
            if (converter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
            }
        }
        
        return restTemplate;
    }
}
